import axios from "axios";
import router from "@/router";
import Cookies from "js-cookie";

const request = axios.create({
    baseURL: 'http://localhost:8888/api/',
    timeout: 5000
})



request.interceptors.request.use(config =>{
    config.headers['Content-Type'] = 'application/json;charset=utf-8';

    const adminJson = Cookies.get('admin')
    if(adminJson){
        // 设置请求头
        config.headers['token'] = JSON.parse(adminJson).token;
    }

    return config
}, error => {
    return Promise.reject(error)
});

//response拦截器
// 可以在接口响应后统一处理结果
request.interceptors.response.use(
    response =>{
        let res = response.data;
        if (response.config.responseType === 'blob') {
            return res
        }
        if (typeof  res === 'string'){
            res = res ? JSON.parse(res) : res
        }
        if (res.code === '401') {
            router.push('/login')
        }
        return res;
    },
    error => {
        console.log('error' + error)
        return Promise.reject(error)
    }
)

export default request